
# coding: utf-8

# In[1]:


# pip install vultr
# pip install ssh2-python 


# 在vultr官网网站注册账号后，可以找到API（可能会询问是否开启）
# 
# ![image.png](attachment:image.png)

# ![image.png](attachment:image.png)

# In[2]:

from __future__ import print_function

from vultr import Vultr
import time


# In[3]:


key = 'YourKey'
if key == 'YourKey':
	print("please change your API KEY in the file ")
	exit()

v = Vultr(key)


# In[4]:


#rlist =v.regions.list()
DCID = 1  # new jersey
VPSPLANID = 201
OSID = 167  # centos 7 x64
#rlist =v.plans.list()


# In[5]:


#v.os.list()


# In[6]:


#rlist['1'.decode()]


# In[7]:


# 创建服务器
pwd = 'haha!@#$%^&*'
sret  = v.server.create(dcid=DCID,osid=OSID,vpsplanid=VPSPLANID,params={'password':pwd})
print(sret)


# In[12]:


print('server create ret ', sret)
SUBID = sret[u'SUBID'].encode()
print('SUBID=',SUBID)
f = open('subid.txt','w')
f.write(SUBID)
f.close()


# In[10]:


# 查询服务器
ct = 0
while True:
    ct=ct+1
    r = v.server.list()
    if len(r) == 0:
        print('\rwait for server created ..' ,ct),
        time.sleep(5)
        continue
    status = r[SUBID.decode()][u'status']
    ip = r[SUBID.decode()][u'main_ip']
    pwd =  r[SUBID.decode()][u'default_password']
    print('\r'+str(ct) + ' '+status+' ip='+ip+' pwd='+pwd),
    if status == 'active':
        break
    else:
        time.sleep(5)

f = open('pwd.txt','w')
f.write(pwd)
f.close()


# In[ ]:


#v.sshkey.list()


# In[ ]:



import os
import socket

from ssh2.session import Session

host = ip # 上面获得的IP
user = 'root'

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, 22))

session = Session()
session.handshake(sock)
#print(session.userauth_list())

print('try login... pwd = '+pwd)

#session.agent_auth(user)
session.userauth_password(
    user, pwd)

print('ok....')

channel = session.open_session()
channel.execute('wget -O install.sh http://yangtf.gitee.io/yingzi/run.sh && chmod +x install.sh && ./install.sh ')
size, data = channel.read()
while size > 0:
    print(data),
    size, data = channel.read()
channel.close()
print("Exit status: %s" % channel.get_exit_status())


# In[ ]:


print("ok")


# In[20]:
